package org.csu.mypetstore.web.servlets;

import com.google.gson.Gson;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.service.AccountService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

//该Servlet用于处理和账号登录、注册等相关的请求
public class AccountServlet extends BaseServlet{
    //主界面，用于退出时返回
    public static final String MAIN = "/WEB-INF/jsp/catalog/Main.jsp";

    //登录相关
    public static final String SIGN_IN = "/WEB-INF/jsp/account/SignonForm.jsp";
    public static final String ERROR = "/WEB-INF/jsp/account/SignonForm.jsp";
    public static final String LOG_IN_SUCCESS = "/WEB-INF/jsp/catalog/Main.jsp";

    //注册相关
    public static final String REGIST = "/WEB-INF/jsp/account/NewAccountForm.jsp";
    public static final String REGIST_SUCCESS = "/WEB-INF/jsp/catalog/Main.jsp";
    public static final String RESIST_FAILED = "/WEB-INF/jsp/account/NewAccountForm.jsp";

    //查看和修改账号信息相关
    public static final String MY_ACCOUNT = "/WEB-INF/jsp/account/IncludeAccountFields.jsp";
    public static final String LOG_IN = "/WEB-INF/jsp/account/SignonForm.jsp";
    public static final String UPDATE_SUCCESS = "/WEB-INF/jsp/account/IncludeAccountFields.jsp";

    //请求登录界面时的处理
    protected void signIn(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("codeError");
        session.removeAttribute("accountNotExist");
        session.removeAttribute("usernameEntered");
        session.removeAttribute("passwordEntered");
        req.getRequestDispatcher(SIGN_IN).forward(req,resp);
    }

    //请求退出时的处理
    protected void signOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("account");
        session.removeAttribute("cart");
        req.getRequestDispatcher(MAIN).forward(req,resp);
    }

    //用户点击登录后在数据库查询
    protected void checkAccount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //使用到的变量
        String username;
        String password;
        String token;//正确的验证码
        String code;//用户输入的验证码
        AccountService service;

        username = req.getParameter("username");
        password = req.getParameter("password");
        //保存到session中
        HttpSession session = req.getSession();
        session.setAttribute("usernameEntered",username);
        session.setAttribute("passwordEntered",password);

        //获取验证码
        token = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        //删除验证码
        session.removeAttribute(KAPTCHA_SESSION_KEY);

        //获取用户输入的验证码
        code = req.getParameter("code");

        //验证码输入正确
        if(token != null && token.equals(code)){
            service = new AccountService();
            Account account = service.getAccount(username, password);
            //账号不存在
            if(account == null){
                session.setAttribute("accountNotExist","Wrong user name or password");
                req.getRequestDispatcher(ERROR).forward(req,resp);
            }
            //登录成功
            else{
                session.setAttribute("account",account);
                req.getRequestDispatcher(LOG_IN_SUCCESS).forward(req,resp);
            }
        }
        //验证码输入错误
        else{
            session.setAttribute("codeError","Verification code error");
            req.getRequestDispatcher(ERROR).forward(req,resp);
        }
    }

    //请求注册界面时的处理
    protected void viewRegisterPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("register_username");
        session.removeAttribute("register_password");
        session.removeAttribute("register_repeated_password");
        session.removeAttribute("passwordFailed");
        session.removeAttribute("usernameFailed");
        session.removeAttribute("codeError");
        req.getRequestDispatcher(REGIST).forward(req,resp);
    }

    //请求在数据库插入账号
    protected void insertAccountInDB(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //需要的一些参数
        String username;
        String password;
        String repeatedPassword;
        String token;
        String code;
        AccountService service;

        HttpSession session = req.getSession();
        //获取验证码
        token = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        //删除验证码
        session.removeAttribute(KAPTCHA_SESSION_KEY);

        session.removeAttribute("passwordFailed");
        session.removeAttribute("usernameFailed");
        session.removeAttribute("codeError");

        username = req.getParameter("username");
        password = req.getParameter("password");
        repeatedPassword = req.getParameter("repeatedPassword");
        code = req.getParameter("code");

        service = new AccountService();

        //如果验证码正确
        if(token != null && token.equalsIgnoreCase(code)){
            //用户名为空
            if("".equals(username)){
                session.setAttribute("register_password",password);
                session.setAttribute("register_repeated_password",repeatedPassword);
                session.setAttribute("usernameFailed","Username can not be null");
                req.getRequestDispatcher(RESIST_FAILED).forward(req,resp);
            }
            //密码为空
            else if("".equals(password)){
                session.setAttribute("register_username",username);
                session.setAttribute("passwordFailed","Password can not be null");
                req.getRequestDispatcher(RESIST_FAILED).forward(req,resp);
            }
            //两次密码不一样
            else if(!password.equals(repeatedPassword)){
                session.setAttribute("register_username",username);
                session.setAttribute("passwordFailed","Two password entries are inconsistent");
                req.getRequestDispatcher(RESIST_FAILED).forward(req,resp);
            }
            //账号已经存在
            else if(service.getAccount(username) != null){
                session.setAttribute("register_password",password);
                session.setAttribute("register_repeated_password",repeatedPassword);
                session.setAttribute("usernameFailed","The username is taken");
                req.getRequestDispatcher(RESIST_FAILED).forward(req,resp);
            }
            //注册成功
            else{
                Account account = new Account();
                account.setUsername(username);
                account.setPassword(password);
                service.insertAccount(account);
                session.setAttribute("account",account);
                req.getRequestDispatcher(REGIST_SUCCESS).forward(req,resp);
            }
        }
        else{
            session.setAttribute("codeError","Verification code error");
            session.setAttribute("register_username",username);
            session.setAttribute("register_password",password);
            session.setAttribute("register_repeated_password",repeatedPassword);
            req.getRequestDispatcher(RESIST_FAILED).forward(req,resp);
        }
    }

    //请求查看当前帐号的信息
    protected void viewAccountInf(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        //判断是否登录，如果登录
        if(session.getAttribute("account") != null){
            req.getRequestDispatcher(MY_ACCOUNT).forward(req,resp);
        }
        //如果没有登录
        else{
            req.getRequestDispatcher(LOG_IN).forward(req,resp);
        }
    }

    //请求修改账号信息
    protected void updateAccountInf(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //需要的一些变量
        AccountService service;

        HttpSession session = req.getSession();
        Account oldAccount = (Account) session.getAttribute("account");
        Account account = new Account();

        account.setUsername(oldAccount.getUsername());
        account.setPassword(oldAccount.getPassword());
        account.setEmail(req.getParameter("account.email"));
        account.setFirstName(req.getParameter("account.firstName"));
        account.setLastName(req.getParameter("account.lastName"));
        account.setAddress1(req.getParameter("account.address1"));
        account.setAddress2(req.getParameter("account.address2"));
        account.setCity(req.getParameter("account.city"));
        account.setState(req.getParameter("account.state"));
        account.setZip(req.getParameter("account.zip"));
        account.setCountry(req.getParameter("account.country"));
        account.setPhone(req.getParameter("account.phone"));
//        String status = req.getParameter();
//        String favouriteCategoryId = req.getParameter("favouriteCategoryId");
//        String languagePreference = req.getParameter("account.languagePreference");
//        boolean listOption = req.getParameter("account.listOption");
//        boolean bannerOption = req.getParameter("account.bannerOption");
//        String bannerName = req.getParameter();
        session.setAttribute("account",account);
        service = new AccountService();
        service.updateAccount(account);
        req.getRequestDispatcher(UPDATE_SUCCESS).forward(req,resp);
    }

    //请求检查用户名是否存在
    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String username = req.getParameter("username");
        AccountService accountService = new AccountService();
        boolean accountExist = false;
        if(accountService.getAccount(username) != null)
            accountExist = true;

        //封装成Map对象
        Map<String,Object> result = new HashMap<>();
        result.put("accountExist",accountExist);
        Gson gson = new Gson();
        String json = gson.toJson(result);
        resp.getWriter().write(json);
    }
}
